import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Select, TreeSelect, DatePicker, Checkbox, message, Dropdown, Menu, Icon, Popover, Upload, notification } from 'antd'
import _ from 'lodash'
import moment from 'moment'

import Ajax from 'lib/Ajax'
import { addConfig } from 'actions/config'
import EditCitizen from './components/editCitizen'
import ExportCitizen from './components/exportCitizen'
import ErrorCitizen from './components/errorCitizen'
import { getNewTreeData, findRowData, getNameByCode, confirmDelete, downloadFile, backUrl } from 'lib/fun'
import BarInfo from 'components/barInfo'

const FormItem = Form.Item;
const SelectTreeNode = TreeSelect.TreeNode;
const Option = Select.Option;
const { RangePicker } = DatePicker;

class ModuleName extends Component {
	constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: [],
      visible: false,
      editType: "",
      rowdata: {},
      treeData: [],
      exportVisible: false,
      errorVisible: false,
      showBar: false,
      barId: "",
      typeId: "",
    }
    this.current = 1;   //当前第几页
    this.total = 0;   //总共多少页
    this.pageSize = 10;   //每页多少行
    this.search = {};
  }

  componentDidMount(){
    const { config, addConfig } = this.props;
    if(!config.genderCode){
      // 性别
      addConfig('genderCode', 7);
    }
    if(!config.nationCode){
      // 民族
      addConfig('nationCode', 5);
    }
    if(!config.degreeCode){
      // 学历
      addConfig('degreeCode', 6);
    }
    if(!config.relationCode){
      // 与户主关系
      addConfig('relationCode', 8);
    }
    if(!config.identTypeCode){
      // 证件类型
      addConfig('identTypeCode', 13);
    }
    if(!config.citizenInfoTypeCode){
      // 人员分类
      addConfig('citizenInfoTypeCode', 29);
    }
    if(!config.householdTypeCode){
      // 户口类型
      addConfig('householdTypeCode', 19);
    }
    // citizen_info_type_code  人员分类没有找着
  	this.loadData();
    if(this.props.common&&this.props.common.user&&this.props.common.user.user&&this.state.treeData.length == 0){
      this.loadArea(this.props.common.user.user.areaId);
    }
  }

  componentWillReceiveProps(nextProps){
    if(nextProps.common.user&&nextProps.common.user.user&&this.state.treeData.length == 0){
      this.loadArea(nextProps.common.user.user.areaId);
    }
    if(nextProps.common.user&&!this.props.common.user){
      this.loadData(nextProps.common.user.user.areaId);
    }
  }

  componentWillUnmount(){
    notification.destroy();
  }

  loadArea = (areaId)=>{
    var self = this;
    if(self.loadAreaState){
      return
    }
    self.loadAreaState = true;
    Ajax({
      url: '/area/list',
      data: {
        areaParentId: areaId,
        perPage: 100
      },
      success: function(data){
        self.setState({
          treeData: data.list
        });
        self.loadAreaState = false;
      },
      error: function(error){
        message.error(error);
        self.loadAreaState = false;
      }
    });
  }

  pageOnChange = (page)=>{
    this.current = page;
    this.loadData();
  }

  showSizeChange = (current, pageSize)=>{
    var page = Math.ceil(((this.current-1)*this.pageSize+1)/pageSize);
    this.pageSize = pageSize;
    this.current = page;
    this.loadData();
  }

  loadData = (id) => {
    var self = this;
    if(!this.props.common.user&&!id||this.state.loading){
      return
    }
    self.setState({
      loading: true
    });
    const { citizenInfoId, areaId, identNumber, name, householdRegisterNumber, master, birthday } = this.search;
    console.log(this.search)
    var birthdayBegin = undefined,
        birthdayEnd = undefined;
    if(birthday != undefined&&birthday.length>0){
      birthdayBegin = birthday[0].format('YYYY-MM-DD');
      birthdayEnd = birthday[1].format('YYYY-MM-DD');
    }
    Ajax({
      url: '/citizen/list',
      data: {
        citizenInfoId,
        areaId: areaId?areaId:(areaId?areaId:(id?id:this.props.common.user.user.areaId)),
        identNumber,
        name,
        householdRegisterNumber,
        master,
        birthdayBegin: birthdayBegin,
        birthdayEnd: birthdayEnd,
        currentPage: self.current,  //请求页码
        perPage: self.pageSize,   //每页数量
      },
      success: function(data){
        self.total = data.totalCount;
        self.setState({
          loading: false,
          data: data.list
        });
      },
      error: function(error){
        self.setState({
          loading: false
        });
        message.error(error);
      }
    });
  }

  handleFilter = (option)=>{
    if(!_.isEqual(option, this.search)){
      this.search = option;
      this.loadData();
    }
  }

  // 操作
  operate = (type, row)=>{
    if(type == 'edit'){
      this.setState({
        visible: true,
        editType: 'edit',
        rowdata: row
      });
    }else{
      this.setState({
        visible: true,
        editType: 'new'
      });
    }
  }

  editOk = (type, rowdata)=>{
    var self = this;
    if(type == 'edit'){
      var find = _.find(self.state.data, (item)=>{
        return item.citizenInfoId == rowdata.citizenInfoId
      });
      if(find){
        Object.assign(find, rowdata);
      }
      self.setState({
        visible: false,
        rowdata: {},
        data: self.state.data
      });
      message.success('修改记录成功！');
    }else{
      self.state.data.unshift(rowdata);
      self.setState({
        visible: false,
        rowdata: {},
        data: self.state.data
      });
      message.success('增加记录成功！');
    }
  }
  editCancel = ()=>{
    this.setState({
      visible: false,
      rowdata: {}
    });
  }
  doDelete = (id)=>{
    var self = this;
    confirmDelete(()=>{
      Ajax({
        url: '/citizen/delete',
        data: {
          "citizenInfoId": id
        },
        success: function(data){
          // _.remove(self.state.data, function(d) {
          //   return d.citizenInfoId == id
          // });
          // self.setState({
          //   data: self.state.data
          // });
          self.loadData();
        },
        error: function(error){
          message.error(error);
        }
      });
    }, ()=>{
      message.info('取消删除');
    });
  }

  exportOk = (b)=>{
    this.setState({
      showBar: false
    });
    b&&(this.current=1)&&this.loadData();
  }

  output = ()=>{
    var self = this;
    const { birthday } = this.search;
    var birthdayBegin = undefined,
        birthdayEnd = undefined;
    if(birthday != undefined&&birthday.length>0){
      birthdayBegin = birthday[0].format('YYYY-MM-DD');
      birthdayEnd = birthday[1].format('YYYY-MM-DD');
    }
    downloadFile('/citizen/downCitizen', Object.assign({}, this.search, {
      birthdayBegin,
      birthdayEnd
    }), {
      start: function(){
        self.setState({
          loading: true
        });
      },
      end: function(){
        self.setState({
          loading: false
        });
      },
    });
  }
  
  render() {
    var self = this;
    const { config } = this.props;
    const columns = [{
      title: '用户姓名',
      dataIndex: 'name'
    }, {
      title: '证件号码',
      dataIndex: 'identNumber'
    }, {
      title: '性别',
      dataIndex: 'genderCode',
      render: (text, record) => (<span>{ getNameByCode(config, 'genderCode', text) }</span>)
    }, {
      title: '民族',
      dataIndex: 'nationCode',
      render: (text, record) => (<span>{ getNameByCode(config, 'nationCode', text) }</span>)
    }, {
      title: '是否户主',
      dataIndex: 'master',
      render: (text, record) => (<span>{ text?"是":"否" }</span>)
    }, {
      title: '户口簿编号',
      dataIndex: 'householdRegisterNumber'
    }, {
      title: '出生年月',
      dataIndex: 'birthday'
    }, {
      title: '行政区划',
      dataIndex: 'areaName'
    }, {
      title: '状态',
      dataIndex: 'disabled',
      render: (text, record) => (<span>{ !text?"启用":"禁用" }</span>)
    }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <Dropdown overlay={
              <Menu>
                <Menu.Item>
                  <a onClick={this.operate.bind(this, "edit", record)} href="javascript:;">编辑</a>
                </Menu.Item>
                <Menu.Item>
                  <a href="javascript:;" onClick={this.doDelete.bind(this, record.citizenInfoId)}>删除</a>
                </Menu.Item>
              </Menu>
            }>
              <a className="ant-dropdown-link" href="javascript:;">
                操作 <Icon type="down" />
              </a>
            </Dropdown>
          </span>
        )
    }];

    var pagination = {
      current: this.current,
      total: this.total,
      pageSize: this.pageSize,
      onChange: this.pageOnChange,
      showSizeChanger: true,
      onShowSizeChange: this.showSizeChange,
      showTotal: total => `总共 ${total} 条`
    };

    const props = {
      name: 'file',
      multiple: false,
      showUploadList: false,
      action: backUrl("/citizen/uploadCitizen"),
      data: {},
      onChange(info) {
        const status = info.file.status;
        if (status == 'uploading') {
          self.setState({
            showBar: true
          });
        }
        if (status === 'done') {
          var result = info.file.response;
          // &&result.data.successCount&&result.data.successCount>0
          if(result.status == 1&&result.data){
            const data = result.data
            self.setState({
              showBar: true,
              barId: data.barId,
              typeId: data.typeId,
            });
          }else{
            notification.error({
              message: '文件上传失败',
              description: result.msg||"未知失败原因",
              duration: 60,
            });
            self.setState({
              showBar: false
            });
          }
        } else if (status === 'error') {
          message.error("文件上传失败");
          self.setState({
            showBar: false
          });
        }
      },
    };

    const content = (
      <Menu>
        <Menu.Item>
          <a href="javascript:;" onClick={()=>{
            downloadFile('/citizen/downTemplate')
          }}>下载导入模版</a>
        </Menu.Item>
        <Menu.Item>
          <Upload {...props}>
            <a href="javascript:;" style={{color: '#666'}}>批量导入人员</a>
          </Upload>
        </Menu.Item>
        <Menu.Item>
          <a href="javascript:;" onClick={()=>{this.setState({errorVisible:true})}}>查看失败人员</a>
        </Menu.Item>
      </Menu>
    );

    return (
    	<div className="area">
        <FilterModule 
          handleFilter={ this.handleFilter }
          treeData={ this.state.treeData }
        />
        <div className="area-con">
          <Table 
            columns={columns}
            dataSource={this.state.data}
            pagination={pagination}
            rowKey="citizenInfoId"
            loading={ this.state.loading }
            title={() => (<div>
                            <Button type="primary" style={{marginRight: 15}} icon="plus" onClick={ this.operate.bind(this, 'new') }>新建</Button>
                            <Dropdown overlay={content}>
                              <Button type="primary" icon="export">批量导入</Button>
                            </Dropdown>
                            <Button type="primary" style={{marginLeft: 15}} icon="download" disabled={this.total <= 0} onClick={ this.output }>导出人员</Button>
                          </div>)}
          />
        </div>
        <EditCitizen 
          visible={ this.state.visible }
          onOk={ this.editOk }
          onCancel={ this.editCancel }
          type={ this.state.editType }
          rowdata={ this.state.rowdata }
          config={ this.props.config}
          treeData={ this.state.treeData }
        />
        <ExportCitizen
          visible={ this.state.exportVisible }
          onClose={ this.exportOk }
          showError={ ()=>{
            this.setState({
              errorVisible: true
            });
          } }
          url='/citizen/uploadCitizen'
          title='批量导入人员信息'
        />
        <ErrorCitizen
          visible={ this.state.errorVisible }
          onClose={ ()=>{
            this.setState({
              errorVisible: false
            });
          } }
          title='批量导入人员信息'
          downFailList='/citizen/downFailList'
          uploadBatchList='/citizen/uploadBatchList'
          failList='/citizen/failList'
          getFail='/citizen/getFail'
          type="upload"
        />
        <BarInfo
          visible={this.state.showBar}
          barId={this.state.barId}
          typeId={this.state.typeId}
          onClose={this.exportOk}
        />
    	</div>
    )
  }
}

function mapStateToProps(state) {
  return {
    config: state.config,
    common: state.common
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ addConfig }, dispatch)
}

module.exports = connect(mapStateToProps,mapDispatchToProps)(ModuleName)


class Filter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: []
    }
  }

  componentDidMount(){
  }

  componentWillReceiveProps(nextProps){

  }

  handleSearch = (e) => {
    var self = this;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      self.props.handleFilter(values);
    });
  }

  handleReset = () => {
    this.props.form.resetFields();

  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const formItemLayout2 = {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
    };

    const genderCode = this.props.genderCode||[]
    return (<Form
          horizontal
          className="ant-advanced-search-form"
          onSubmit={this.handleSearch}
        >
          <Row gutter={10}>
            <Col span={6}>
              <FormItem {...formItemLayout} label="行政区划">
                {getFieldDecorator("areaId")(
                  <Select
                    size="default"
                    allowClear
                  >
                    {
                      (this.props.treeData||[]).map(function(obj){
                        return (<Option key={obj.areaId+""} value={ obj.areaId+"" }>{ obj.areaName }</Option>)
                      })
                    }
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="用户姓名">
                {getFieldDecorator("name")(
                  <Input />
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="身份证">
                {getFieldDecorator("identNumber")(
                  <Input />
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="是否户主">
                {getFieldDecorator("master", {
                  valuePropName: 'checked'
                })(
                  <Checkbox />
                )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={10}>
            <Col span={6}>
              <FormItem {...formItemLayout} label="户口簿编号">
                {getFieldDecorator("householdRegisterNumber")(
                  <Input />
                )}
              </FormItem>
            </Col>
            <Col span={11}>
              <div style={{marginLeft: 10}}>
                <FormItem {...formItemLayout2} label="出生日期">
                  {getFieldDecorator("birthday")(
                    <RangePicker />
                  )}
                </FormItem>
              </div>
            </Col>
            <Col span={7} style={{textAlign: 'right'}}>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                重置
              </Button>
            </Col>
          </Row>
        </Form>);
  }
}

var FilterModule = Form.create()(Filter)